<template>
  <div class="pay-container">
    <!-- 账户余额 -->
    <div class="user-info">
      <div class="title">Balance</div>
      <div class="info">
        <img src="@/assets/pay/goldCoin.png" alt="" />
        <span>{{ userPrice }}</span>
      </div>
    </div>
    <!-- 金币列表 -->
    <div class="coins-list">
      <div
        v-for="(item, index) in coins_list.data"
        :key="item"
        @click="openPay(item)"
        class="item"
      >
        <img :src="item.images" alt="" />
        <p v-if="index != 0" class="fixed">
          <span class="num">20%</span>
          <span class="more">more</span>
        </p>
        <p class="quantity">{{ item.cost_price }}</p>
        <p class="pay-btn">{{ item.price_formatted }}</p>
      </div>
    </div>
    <!-- 支付弹窗 -->
    <el-dialog
      v-model="pay_visible"
      lock-scroll
      style="width: 600px"
      :before-close="handleClose"
    >
      <div class="game-info">
        <img :src="game_info.images[0].popup" alt="" />
        <div class="text">
          <p>{{ game_info.cost_price }}</p>
          <p>
            {{ game_info.skus[0].price_format }}
          </p>
        </div>
      </div>
      <header>
        <p class="title">PAYMENT METHODS</p>
        <p class="text">We accept the following secure payment methods :</p>
        <div class="icons">
          <img src="@/assets/pay/3.png" alt="" />
          <img src="@/assets/pay/2.png" alt="" />
          <img src="@/assets/pay/4.png" alt="" />
          <img src="@/assets/pay/1.png" alt="" />
        </div>
      </header>
      <el-form
        ref="paypalFormRef"
        :model="paypalForm"
        :rules="paypalRules"
        label-width="auto"
        label-position="top"
        status-icon
        autocomplete="off"
        hide-required-asterisk
        class="credit-form"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="methods">
              <el-select v-model="pay_kind">
                <el-option label="PayPal" value="1" />
                <el-option label="Credit Card" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- paypal 支付 -->
          <el-col v-if="pay_kind == 1" :span="24">
            <el-form-item prop="email">
              <el-input
                v-model="paypalForm.email"
                placeholder="example@email.com"
              />
            </el-form-item>
          </el-col>
          <!-- 信用卡 支付 -->
          <el-col v-if="pay_kind == 2" :span="24">
            <el-form-item prop="CARDNO">
              <el-input v-model="paypalForm.CARDNO" placeholder="Card Number" />
            </el-form-item>
          </el-col>
          <el-col v-if="pay_kind == 2" :span="12">
            <el-form-item prop="ExpiryData">
              <el-date-picker
                v-model="paypalForm.ExpiryData"
                type="month"
                placeholder="MM/YY"
                format="MM/YY"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="pay_kind == 2" :span="12">
            <el-form-item prop="CVV">
              <el-input
                v-model="paypalForm.CVV"
                placeholder="Security code"
                :suffix-icon="Postcard"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="pay_kind == 2" :span="24">
            <el-form-item prop="CARDHolderName">
              <el-input
                v-model="paypalForm.CARDHolderName"
                placeholder="Cardholder name"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button @click="handlePaypal(paypalFormRef)"
                >Pay Now</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { productList, productDetails } from "@/api/product";
import { addCart, deleteAll } from "@/api/cart";
import { show, paypal } from "@/api/order";
import { confirm } from "@/api/checkout";
import { userSpecies } from "@/api/user";
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";

const pay_visible = ref(false);

// 初始化 清空购物车
const deleteAllCart = async () => {
  await deleteAll();
};
deleteAllCart();

// 获取当前账户金币
const userPrice = ref("");
const getUserSpecies = () => {
  userSpecies().then((res) => {
    userPrice.value = res.data.price;
  });
};
getUserSpecies();

// 获得金币列表
const coins_list = ref([]);
const getProductData = () => {
  productList({
    category_id: [100299],
    brand_id: 18,
    per_page: 100,
  }).then((res) => {
    coins_list.value = res.data;
    // console.log(coins_list.value);
  });
};
getProductData();

// 打开支付弹窗
const pay_kind = ref("1");
const game_info = ref({});
const openPay = (item) => {
  productDetails(item.id).then((res) => {
    game_info.value = res.data.product;
    game_info.value.cost_price = item.cost_price;

    // 加车
    addCart({
      sku_id: game_info.value.skus[0].id,
      quantity: "1",
    }).then(() => {
      pay_visible.value = true;
    });
  });
};

// paypal配置
const paypalFormRef = ref(null);
const paypalForm = reactive({
  // paypal 信息
  email: "", // hdgsrichelle@yahoo.com
  username: "", // 网站昵称或者网站邮箱
  amount: "",
  ip: "127.0.0.1",
  customer: "bytetapper",

  // 信用卡信息
  CARDNO: "", // 4514617650488994
  ExpiryData: "",
  CVV: "",
  CARDHolderName: "",
});
const paypalRules = reactive({
  // paypal 校验
  email: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "the format is incorrect!",
      trigger: "blur",
    },
  ],
  // 信用卡校验
  CARDNO: [
    {
      pattern:
        /^(?:4[0-9]{12}(?:[0-9]{3})?)$/ ||
        /^(?:5[1-5][0-9]{14})$/ ||
        /^(?:3[47][0-9]{13})$/ ||
        /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/,
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  CVV: [
    { min: 3, max: 3, message: "Length should be 3", trigger: "blur" },
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  ExpiryData: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  CARDHolderName: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
});

// paypal支付
const handlePaypal = async (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 下单
      confirm({
        website: "bytetapper",
      }).then((res) => {
        // 获取订单详情
        show(res.data.number).then((res) => {
          paypalForm.username = res.data.email;
          paypalForm.amount = res.data.total_format;
          // console.log('订单号:', res.data.number);

          // paypal 支付
          if (pay_kind.value == 1) {
            paypal(res.data.number, { ...paypalForm })
              .then((res) => {
                // console.log("paypal支付链接:", res.data.paylink);
                ElMessageBox.confirm(
                  "You are about to jump to a new page to make the payment!",
                  {
                    confirmButtonText: "sure",
                    cancelButtonText: "cancel",
                    customClass: "messageBox",
                    type: "",
                    showClose: false,
                  }
                )
                  .then(() => {
                    if (res.data.paylink) {
                      window.open(res.data.paylink);
                      pay_visible.value = false;
                      router.push('/')
                    }
                  })
                  .catch(() => {});
              })
              .catch((res) => {
                ElMessage({
                  message: "Failed to pay !",
                  type: "error",
                });
                pay_visible.value = false;
              });
          } else {
            // 信用卡支付
            pay_visible.value = false;
            ElMessage.error("Payment failed!");
            return;
          }
        });
      });
    } else {
      return false;
    }
  });
};

// 关闭弹窗
const handleClose = () => {
  deleteAllCart(); // 清空购物车

  paypalForm.email = "";
  paypalForm.username = "";
  paypalForm.amount = "";

  pay_visible.value = false;
};
</script>

<style lang="scss" scoped>
.pay-container {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .user-info {
    margin-bottom: 60px;

    .title {
      font-size: 22px;
      font-weight: bold;
      color: #ffa330;
      padding-bottom: 20px;
    }
    .info {
      display: flex;
      align-items: center;
      img {
        margin-right: 10px;
        width: 30px;
        height: 30px;
      }
      span {
        font-size: 18px;
        font-weight: bold;
        color: #d2c50f;
      }
    }
  }
  .coins-list {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    // grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 20px;
    .item {
      padding: 20px;
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      border-radius: 6px;
      background: linear-gradient(
        to top,
        rgba(255, 255, 255, 0),
        rgba(0, 107, 255, 0.1) 100%
      );
      box-shadow: inset 0px 1px 2px rgba(150, 146, 146, 0.25),
        0px 2px 2px rgba(0, 0, 0, 0.44);
      transition: all 0.5s;
      cursor: pointer;
      img {
        margin-bottom: 10px;
        width: 60px;
        height: 60px;
        border-radius: 10px;
        object-fit: cover;
      }
      .quantity {
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 700;
        color: #f6f60e;
      }
      .pay-btn {
        width: 100%;
        height: 35px;
        line-height: 35px;
        // background: linear-gradient(90deg, #f4c973, #f8dc9f);
        background: #27142d;
        border-radius: 8px;
        font-size: 16px;
        font-weight: bold;
        color: #fff;
        text-align: center;
        display: inline-block;
      }
      .fixed {
        padding: 6px 4px;
        position: absolute;
        top: 6px;
        right: 6px;
        // border-top: 2px solid yellow;
        border-radius: 4px;
        // border-top-left-radius: 0;
        // border-top-right-radius: 0;
        // background: linear-gradient(90deg, #f4c973, #f8dc9f);
        background: #332139;
        span {
          // display: block;
          text-align: center;
        }
        .num {
          font-size: 16px;
          font-weight: bold;
          color: #fff;
        }
        .more {
          font-size: 12px;
          color: #fff;
        }
      }
      &:hover {
        transform: scale(0.96);
      }
    }
  }
  ::v-deep .el-dialog {
    background: rgb(36, 36, 46);
    .el-dialog__header {
      position: absolute;
      top: 0px;
      right: -80px;
      .el-dialog__headerbtn {
        padding: 10px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        .el-icon {
          font-size: 30px;
          color: #fff;
        }
        &:hover {
          background: #444;
        }
      }
    }
    .el-dialog__body {
      .game-info {
        margin-bottom: 20px;
        display: flex;
        img {
          margin-right: 20px;
          width: 80px;
          height: 80px;
          border-radius: 4px;
          object-fit: cover;
        }
        .text {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          p:nth-child(1) {
            margin-bottom: 6px;
            font-size: 20px;
            font-weight: bold;
            color: #f6f60e;
          }
          p:nth-child(2) {
            font-size: 16px;
            color: #fff;
          }
        }
      }
      header {
        margin-bottom: 20px;
        .title {
          margin-bottom: 10px;
          font-size: 18px;
          color: #b4b7b7;
        }
        .text {
          margin-bottom: 16px;
          font-size: 16px;
          color: #b4b7b7;
        }
        .icons {
          img {
            padding: 4px;
            margin-right: 10px;
            width: 60px;
            height: 30px;
            object-fit: contain;
            border: 1px solid #b4b7b7;
            border-radius: 4px;
            background: #fff;
          }
        }
      }
      .el-form {
        padding: 20px;
        margin-bottom: 20px;
        border-radius: 4px;
        border: 2px solid #525050;
        .el-select {
          width: 200px;
          .el-select__wrapper {
            box-shadow: none !important;
            .el-select__selected-item {
              color: #333;
              box-shadow: none !important;
            }
          }
        }
        .el-input {
          --el-input-hover-border: none !important;
          --el-input-text-color: none !important;
          --el-input-focus-border: none !important;
          --el-input-focus-border-color: none !important;
          box-shadow: none !important;
          .el-input__wrapper {
            border: 1px solid #000;
            box-shadow: none !important;
            --el-input-hover-border: none !important;
            --el-input-text-color: none !important;
            --el-input-focus-border: none !important;
            --el-input-focus-border-color: none !important;
            .el-input__inner {
              color: #333;
            }
          }
        }
        .el-button {
          width: 200px;
          height: 40px;
          color: #fff;
          background: #15a251;
          border: none;
          &:hover {
            background: #25b564;
          }
        }
      }
    }
  }
}
</style>
